package com.br.ufrn.laut.braipetro.app.conexao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.apache.http.client.methods.HttpGet;

import android.util.Log;

public class ComunicacaoJSON {

    private InputStream inputStream = null;
    private JSONArray jsonArray = null;

    // constructor
    public ComunicacaoJSON() {

    }

    public JSONArray getJSON (String url) {

        String result = "";
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();

            // make GET request to the given URL
            HttpResponse httpResponse = httpClient.execute(new HttpGet(url));

            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // convert inputstream to string
            if(inputStream != null)
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            inputStream, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;

                    while ((line = reader.readLine()) != null) {
                        result += line;
                    }
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("Erro no Buffer", "Conversão de dados com erros " + e.toString());
                }
            else
                result = "Sem dados para exibir!";

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        // try parse the string to a JSON object
        try {
            jsonArray = new JSONArray(result);
        } catch (JSONException e) {
            Log.e("Erro", "Conversão para JSON com erros " + e.toString());
        }
        // return JSON String
        return jsonArray;
    }
}

